import React from 'react';
import axios from 'axios';

export default class FetchUser extends React.PureComponent {
  state = {
    user: {},
  };

  getUser = () => {
    const { id } = this.props;
    // axios 方式获取设置用户
    axios.get(`https://xiaozhu.run/api/user/${id}`).then(resp => {
      // console.log(`resp`, resp);
      // const username = resp.data.data.username;
      // 直接修改 BAD
      // this.state.user.username = username;
      // OK
      // const newUser = { ...this.state.user };
      // immutable.js
      // newUser.username = username;
     
      this.setState({ user: resp.data.data });
    });

    // fetch 方式获取设置用户
    // fetch('https://xiaozhu.run/api/user/9527').then(r => {
    //   r.json().then(resp => {
    //     this.setState({ user: resp.data });
    //   });
    // });
  };

  componentDidMount() {
    console.log('componentDidMount');
    this.getUser();
  }

  // shouldComponentUpdate(nextProps, nextState) {
  //   console.log('shouldComponentUpdate');
  //   if (nextState.user === this.state.user) {
  //     return false;
  //   }
  //   return true;
  // }

  componentDidUpdate(prevProps) {
    console.log('componentDidUpdate');
    if (prevProps.id !== this.props.id) {
      this.getUser();
    }
  }

  render() {
    const { user } = this.state;
    return (
      <div>
        <p>ID: {user.id}</p>
        <p>Username: {user.username}</p>
      </div>
    );
  }
}
